package transporter

import (
	"bufio"
	"encoding/hex"
	"net"
)

type Transporter interface {
	Receive() ([]byte, error)
	Send(data []byte) error
	Close() error
}

type hexTransporter struct {
	conn     net.Conn
	receiver *bufio.Reader
	sender   *bufio.Writer
}

func NewHexTransporter(conn net.Conn) *hexTransporter {
	receiver := bufio.NewReader(conn)
	sender := bufio.NewWriter(conn)
	return &hexTransporter{
		conn:     conn,
		receiver: receiver,
		sender:   sender,
	}
}
func (t *hexTransporter) Send(data []byte) error {
	data = hexEncoder(data)
	_, err := t.sender.Write(data)
	if err != nil {
		return err
	}
	return t.sender.Flush()
}
func (t *hexTransporter) Receive() ([]byte, error) {
	data, err := t.receiver.ReadBytes('\n')
	if err != nil {
		return nil, err
	}
	data = hexDecode(data)
	return data, nil
}
func (t *hexTransporter) Close() error {
	return t.conn.Close()
}

func hexDecode(data []byte) []byte {
	n := len(data) / 2
	ret := make([]byte, n)
	_, err := hex.Decode(ret, data[:n*2])
	if err != nil {
		panic(err)
	}
	return ret

}
func hexEncoder(data []byte) []byte {
	n := len(data)
	ret := make([]byte, 2*n+1)

	// 使用标准库的hex.Encode函数进行十六进制编码
	// 将data的内容编码到ret的前2*n个字节中
	hex.Encode(ret, data)
	ret[n*2] = '\n'
	return ret
}
